<template>
  <div class="data-backup p-4">
    <!-- 页面标题 -->
    <div class="mb-4 flex justify-between items-center">
      <h2 class="text-lg font-medium">数据备份管理</h2>
      <el-button type="primary" @click="handleAdd">
        <div class="i-carbon-add mr-1"></div>添加任务
      </el-button>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="定时配置" name="config">
        <!-- 搜索栏 -->
        <div class="mb-4 flex items-center gap-4">
          <el-input
            v-model="searchKey"
            placeholder="请输入任务key"
            class="w-60"
            clearable
          >
            <template #prefix>
              <div class="i-carbon-search"></div>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>

        <!-- 任务列表 -->
        <div class="bg-white rounded-lg shadow-md">
          <ArtTable :data="taskList" :loading="loading" border stripe>
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="taskKey" label="任务key" min-width="120" />
            <el-table-column prop="taskDesc" label="任务描述" min-width="150" />
            <el-table-column prop="cronExpression" label="任务表达式" min-width="120" />
            <el-table-column prop="createTime" label="创建时间" min-width="160" align="center" sortable />
            <el-table-column label="是否启动初始化" width="120" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.isInit"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleInitChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="任务状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '运行中' : '已停止' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" align="center" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    v-if="scope.row.status === 0"
                    type="primary"
                    link
                    @click="handleStart(scope.row)"
                  >
                    <div class="i-carbon-play mr-1"></div>启动
                  </el-button>
                  <el-button
                    v-else
                    type="warning"
                    link
                    @click="handleStop(scope.row)"
                  >
                    <div class="i-carbon-pause mr-1"></div>停止
                  </el-button>
                  <el-button
                    v-if="scope.row.status === 1"
                    type="info"
                    link
                    @click="handleRestart(scope.row)"
                  >
                    <div class="i-carbon-restart mr-1"></div>重启
                  </el-button>
                  <el-button type="primary" link @click="handleEdit(scope.row)">
                    <div class="i-carbon-edit mr-1"></div>编辑
                  </el-button>
                  <el-button type="danger" link @click="handleDelete(scope.row)">
                    <div class="i-carbon-trash-can mr-1"></div>删除
                  </el-button>
                  <el-button type="success" link @click="handleViewLog(scope.row)">
                    <div class="i-carbon-document mr-1"></div>日志
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </ArtTable>

          <!-- 分页 -->
          <div class="mt-4 flex justify-end p-4">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="任务日志" name="log">
        <!-- 日志搜索栏 -->
        <div class="mb-4 flex items-center gap-4">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="w-80"
          />
          <el-input
            v-model="logSearchKey"
            placeholder="请输入任务key"
            class="w-60"
            clearable
          >
            <template #prefix>
              <div class="i-carbon-search"></div>
            </template>
          </el-input>
          <el-button type="primary" @click="handleLogSearch">搜索</el-button>
        </div>

        <!-- 日志列表 -->
        <div class="bg-white rounded-lg shadow-md">
          <ArtTable :data="logList" :loading="logLoading" border stripe>
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="taskKey" label="任务key" min-width="120" />
            <el-table-column prop="taskDesc" label="任务描述" min-width="150" />
            <el-table-column prop="cronExpression" label="任务表达式" min-width="120" />
            <el-table-column prop="filePath" label="文件路径" min-width="200" />
            <el-table-column prop="executeTime" label="执行时间" min-width="160" align="center" sortable />
            <el-table-column label="是否成功" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.success ? 'success' : 'danger'">
                  {{ scope.row.success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </ArtTable>

          <!-- 日志分页 -->
          <div class="mt-4 flex justify-end p-4">
            <el-pagination
              v-model:current-page="logCurrentPage"
              v-model:page-size="logPageSize"
              :total="logTotal"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleLogSizeChange"
              @current-change="handleLogCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加/编辑任务弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑任务' : '添加任务'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="任务key" prop="taskKey">
          <el-input v-model="form.taskKey" placeholder="请输入任务key" />
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="form.taskDesc" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="任务表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式">
            <template #append>
              <el-popover
                placement="right"
                title="Cron表达式说明"
                :width="300"
                trigger="click"
              >
                <template #reference>
                  <el-button>帮助</el-button>
                </template>
                <div class="text-sm">
                  <p>Cron表达式格式：秒 分 时 日 月 周</p>
                  <p>示例：</p>
                  <p>0 0 2 * * ? - 每天凌晨2点执行</p>
                  <p>0 0 2 1 * ? - 每月1号凌晨2点执行</p>
                  <p>0 0/30 * * * ? - 每30分钟执行一次</p>
                </div>
              </el-popover>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否初始化">
          <el-switch
            v-model="form.isInit"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看日志弹窗 -->
    <el-dialog
      v-model="logDialogVisible"
      title="任务执行日志"
      width="800px"
    >
      <div class="h-96 overflow-auto bg-gray-50 p-4 rounded">
        <pre class="text-sm">{{ currentLog }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据定义
const activeTab = ref('config')
const loading = ref(false)
const logLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const logCurrentPage = ref(1)
const logPageSize = ref(10)
const logTotal = ref(0)
const searchKey = ref('')
const logSearchKey = ref('')
const dateRange = ref([])
const dialogVisible = ref(false)
const logDialogVisible = ref(false)
const isEdit = ref(false)
const currentLog = ref('')

// 表单数据
const formRef = ref<FormInstance>()
const form = reactive({
  taskKey: '',
  taskDesc: '',
  cronExpression: '',
  isInit: 0
})

// 表单校验规则
const rules = {
  taskKey: [{ required: true, message: '请输入任务key', trigger: 'blur' }],
  taskDesc: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
  cronExpression: [{ required: true, message: '请输入任务表达式', trigger: 'blur' }]
}

// 模拟数据
const taskList = ref([
  {
    taskKey: 'ZLJC',
    taskDesc: '质量检测',
    cronExpression: '0/59 * * * * ?',
    createTime: '2019-11-04 13:56:47',
    isInit: 1,
    status: 0
  },
  {
    taskKey: 'SJBF',
    taskDesc: '定时任务',
    cronExpression: '0/59 * * * * ?',
    createTime: '2019-10-30 14:12:22',
    isInit: 0,
    status: 1
  }
])

const logList = ref([
  {
    taskKey: 'ZLJC',
    taskDesc: '质量检测',
    cronExpression: '0/59 * * * * ?',
    filePath: '/backuplog/ars_zkpt1574820599001.sql',
    executeTime: '2023-06-12 16:07:00',
    success: false
  },
  {
    taskKey: 'YZXJC',
    taskDesc: '代码标准一致性检查',
    cronExpression: '0/59 * * * * ?',
    filePath: '',
    executeTime: '2020-08-09 16:43:00',
    success: true
  }
])

// 方法定义
const handleSearch = () => {
  // TODO: 实现搜索功能
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleLogSearch = () => {
  // TODO: 实现日志搜索功能
  logLoading.value = true
  setTimeout(() => {
    logLoading.value = false
  }, 500)
}

const handleAdd = () => {
  isEdit.value = false
  form.taskKey = ''
  form.taskDesc = ''
  form.cronExpression = ''
  form.isInit = 0
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    type: 'warning'
  }).then(() => {
    // TODO: 实现删除功能
    ElMessage.success('删除成功')
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现提交功能
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
    }
  })
}

const handleInitChange = (row: any) => {
  // TODO: 实现初始化状态切换功能
  ElMessage.success(`${row.isInit ? '启用' : '禁用'}初始化成功`)
}

const handleStart = (row: any) => {
  // TODO: 实现启动任务功能
  row.status = 1
  ElMessage.success('启动成功')
}

const handleStop = (row: any) => {
  // TODO: 实现停止任务功能
  row.status = 0
  ElMessage.success('停止成功')
}

const handleRestart = (row: any) => {
  // TODO: 实现重启任务功能
  ElMessage.success('重启成功')
}

const handleViewLog = (row: any) => {
  currentLog.value = `任务key: ${row.taskKey}
任务描述: ${row.taskDesc}
执行时间: ${row.createTime}
执行结果: 成功
详细日志:
[INFO] 开始执行数据备份任务
[INFO] 正在备份数据库...
[INFO] 数据备份完成
[INFO] 备份文件已保存到: /backuplog/backup_${row.taskKey}_${Date.now()}.sql
[INFO] 任务执行完成`
  logDialogVisible.value = true
}

// 分页方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // TODO: 重新加载数据
}

const handleLogSizeChange = (val: number) => {
  logPageSize.value = val
  // TODO: 重新加载日志数据
}

const handleLogCurrentChange = (val: number) => {
  logCurrentPage.value = val
  // TODO: 重新加载日志数据
}
</script>

<style scoped>
.data-backup {
  .el-button-group {
    .el-button {
      margin-left: 0 !important;
    }
  }
}
</style> 